package com.qifan.energy.http.net;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.StringUtils;
import com.qifan.energy.global.Constant;
import com.qifan.energy.global.MyApplication;
import com.qifan.energy.http.request.BaseUrlInterceptor;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 */
public class RetrofitFactory {

    private OkHttpClient.Builder okHttpBuilder;
    private Retrofit retrofit;
    private ApiService apiService;
    /**
     * 请求失败重连次数
     */
    private int RETRY_COUNT = 0;
    private static final int DEFAULT_CONNECT_TIMEOUT = 30;
    private static final int DEFAULT_WRITE_TIMEOUT = 30;
    private static final int DEFAULT_READ_TIMEOUT = 30;
    private String token = "";

    //构造方法私有
    private RetrofitFactory() {
        init();
    }

    //初始化Retrofit&&HttpService类对象
    private void init() {
        //手动创建一个OkHttpClient并设置文件缓存|超时时间
        okHttpBuilder = new OkHttpClient.Builder();
        //缓存
        File cacheFile = new File(MyApplication.getContext().getCacheDir(), "cache");
        //100Mb
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100);

        okHttpBuilder.connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
        okHttpBuilder.writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
        okHttpBuilder.addInterceptor(getHeaderInterceptor());
        okHttpBuilder.addInterceptor(new BaseUrlInterceptor());
        okHttpBuilder.addInterceptor(getLoggingInterceptor());
        okHttpBuilder.cache(cache);

        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BaseUrl8085)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpBuilder.build())
                .build();
        //初始化ApiService
        apiService = retrofit.create(ApiService.class);
    }

    private Interceptor getHeaderInterceptor(){
        //增加头部信息
        Interceptor headerInterceptor = chain -> {
            Request.Builder builder = chain.request().newBuilder()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("charset", "utf-8");
            if (!StringUtils.isEmpty(getToken())){
                /*builder.addHeader("token",getToken());*/
                String authorization  = "Bearer " + getToken();
                Logger.i("token->authorization->:",authorization);
                builder.addHeader("Authorization",authorization);
            }
            Request request = builder.build();
            return chain.proceed(request);
        };
        return headerInterceptor;
    }

    private HttpLoggingInterceptor getLoggingInterceptor(){
        // Log信息拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NonNull String s) {
                Logger.i(s);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

    //更换BaseURL
    private void changeBaseUrl(String baseUrl) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpBuilder.build())
                .build();
        //初始化ApiService
        apiService = retrofit.create(ApiService.class);
    }


    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final RetrofitFactory INSTANCE = new RetrofitFactory();
    }

    //获取单例
    public static synchronized RetrofitFactory getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 获取retrofit
     *
     * @return
     */
    public Retrofit getRetrofit() {
        return retrofit;
    }

    /**
     * 获取HttpService
     *
     * @return
     */
    public ApiService getHttpService() {
        return apiService;
    }

    /* 重置token */
    public void setToken(String token) {
        this.token = token;
        init();
    }

    /* 获取token */
    public String getToken() {
        return token;
    }

    /**
     * 设置订阅 和 所在的线程环境
     */
    public <T> void toSubscribe(Observable<T> o, DisposableObserver<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .retry(RETRY_COUNT)//请求失败重连次数
                .subscribe(s);
    }
}
